package com.walking.controller;

import com.walking.entity.User;
import com.walking.repository.UserRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

/**
 * JPA
 * @author walking
 * 公众号：编程大道
 */
@RestController
@RequestMapping("/users")
@Slf4j
public class UserController {

    @Autowired
    private UserRepository userRepository;

    /**
     * 自定义查询
     * @param name
     * @param age
     * @return
     */
    @GetMapping("/{name}/{age}")
    public User getUserByNameAndAge(@PathVariable("name") String name,@PathVariable("age") int age) {
        User user = userRepository.findByUserNameAndUserAge(name, age);
        return user;
    }

    /**
     * 原生SQL
     * @param name
     * @param age
     * @return
     */
    @GetMapping("/sql/{name}/{age}")
    public User getUserByNameAndAgeBySQL(@PathVariable("name") String name,@PathVariable("age") int age) {
        Optional<User> byNameAndAgeBySql = userRepository.findByNameAndAgeBySql(name, age);

        int sexBySql = userRepository.findSexBySql(name, age);
        log.info("原生SQL，只查询一列Sex：{}",sexBySql);

        Map bySqlToMap = userRepository.findBySqlToMap(name, age);
        HashMap map = new HashMap();
        map.putAll(bySqlToMap);
        log.info("原生SQL，转为map：{}",map);

        return byNameAndAgeBySql.orElseGet(User::new);
    }

    /**
     * 自带的查询方法
     * @param userId
     * @return
     */
    @GetMapping("/{id}")
    public User getUserInfo(@PathVariable("id") int userId) {
        Optional<User> optional = userRepository.findById(userId);
        return optional.orElseGet(User::new);
    }

    @PostMapping()
    public User saveUser(@RequestBody User user) {
        return userRepository.save(user);
    }

    @DeleteMapping("/{id}")
    public void deleteUser(@PathVariable("id") int userId) {
        userRepository.deleteById(userId);
    }

    @PutMapping("/{id}")
    public User updateUser(@PathVariable("id") int userId, @RequestBody User user) {
        user.setUserId(userId);
        return userRepository.saveAndFlush(user);
    }


    @GetMapping("/list")
    public Page<User> pageQuery(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) {
        return userRepository.findAll(PageRequest.of(pageNum - 1, pageSize));
    }

}
